package recursive;

/**
 * @author pengfei.hpf
 * @date 2020/3/7
 * @verdion 1.0.0
 */
public class MyPow {
    //TODO: 整形溢出情况!!!! -1.00000  -2147483648 (-Integer.MAX_VALUE)!!!! 如果换成正数是溢出的!!!!

    public double myPow(double x, int n) {
        double isSmall = n > 0? 1: -1;

        long num = n; //防止溢出 变成long型
        num *= isSmall;
        double res = pow(x, num);
        if(isSmall < 0){
            return 1/res;
        }
        return res;
    }

    private double pow(double x, long n){
        if(n == 0){
            return 1;
        }
        long half = n/2;
        double hv = pow(x, half);
        if(n %2 == 0){
            return hv * hv;
        } else {
            return hv * x * hv;
        }
    }
}
